package com.quest.space.websocket;

import java.net.URI;
import java.util.concurrent.ExecutionException;
import com.quest.space.data.WebSocketMsg;
import com.quest.space.poker.biz.WebSocketService;
import com.quest.space.poker.biz.impl.WebSocketServiceImpl;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
public class StompClient {
    private static StompSession session;

    public static StompSession initSession() {
        WebSocketStompClient stompClient = new WebSocketStompClient(new StandardWebSocketClient());
        stompClient.setMessageConverter(new StringMessageConverter());
        stompClient.setInboundMessageSizeLimit(1024 * 1024);
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.afterPropertiesSet();
        stompClient.setTaskScheduler(taskScheduler);
        StompSessionHandler customHandler = new CustomStompSessionHandler();
        StompHeaders stompHeaders = new StompHeaders();
        URI uri = URI.create("ws://localhost:8081/stomp/websocket?token=zw");
        try {
            session = stompClient.connect(uri, null, stompHeaders, customHandler).get();
        } catch (InterruptedException | ExecutionException e) {
        }
        return session;
    }

    public static void sendMessage(String topic, WebSocketMsg msg) {
        /*if(session == null || !session.isConnected()){
            session = initSession();
        }
        session.send(topic, JSON.toJSONString(msg));*/
        handleClientMsg(msg);
    }

    public static void handleClientMsg(WebSocketMsg msg) {
        WebSocketService webSocketService = new WebSocketServiceImpl();
        webSocketService.handleMsg(msg);
    }
}
